﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mapbox.Unity.Map;
using Mapbox.Map;
using Mapbox.Utils;

public class RouteCache : MonoBehaviour
{
    private int visibleBuffer;
    private AbstractMap map;

    // Use this for initialization
    void Start()
    {
        visibleBuffer = GetComponent<CameraBoundsTileProvider>().VisibleBuffer;
        map = GetComponent<AbstractMap>();
    }

    public void UpdateCache(Vector2d coordinate)
    {
        if (map == null)
            return;
        AddTile(GetCurrentTile(coordinate));
        AddRoutePoint(coordinate);
    }

    private UnwrappedTileId GetCurrentTile(Vector2d coordinate)
    {
        return TileCover.CoordinateToTileId(coordinate, map.AbsoluteZoom);
    }

    private void AddTile(UnwrappedTileId centerTile)
    {
        //UnwrappedTileId temp;
        //for (int i = -1; i < 2; i++)
        //{
        //    for (int j = -1; j < 2; j++)
        //    {
        //        temp = new UnwrappedTileId(map.AbsoluteZoom, centerTile.X + i, centerTile.Y + j);
        //        if (!RouteModel.Instance.RouteTileCache.Contains(temp))
        //        {
        //            RouteModel.Instance.RouteTileCache.Add(temp);
        //        }
        //    }
        //}
        if (!RouteModel.Instance.RouteTileCache.Contains(centerTile))
        {
            RouteModel.Instance.RouteTileCache.Add(centerTile);
        }
    }

    private void AddRoutePoint(Vector2d coordinate)
    {
        int count = RouteModel.Instance.RoutePointCache.Count;
        if (count > 0)
        {
            Vector2d last = RouteModel.Instance.RoutePointCache[count - 1];
            if(last.x != coordinate.x || last.y != coordinate.y)
            {
                RouteModel.Instance.RoutePointCache.Add(coordinate);
            }
        }
        else if(count == 0)
        {
            RouteModel.Instance.RoutePointCache.Add(coordinate);
        }
    }
}
